var express = require('express');
const { Users } = require('../db/Schemas/user')
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});


router.post('/register', async(req, res) => {

    let newUser = new Users(req.body)

    await newUser.save().then(() => {
        res.send({
            code: 200,
            message: '注册成功'
        })
    }).catch(error => {
        res.send({
            code: 500,
            message: error
        })
    })
})

router.post('/login', async(req, res) => {
    let loginUser = req.body
    console.log(loginUser)
    let userName = loginUser.userName
    let password = loginUser.password
    await Users.findOne({ userName: userName }).exec().then(async(result) => {
        console.log(result)
        if (result) {
            let newUser = new Users()
            await newUser.comparePassword(password, result.password)
                .then(isMatch => {
                    res.send({ code: 200, message: isMatch })
                })
                .catch(error => {
                    console.log(error)
                    res.send({ code: 500, message: error })
                })
        } else {
            res.send({ code: 200, message: '用户名不存在' })
        }
    }).catch(error => {
        console.log(error)
        res.send({ code: 500, message: error })
    })

})


module.exports = router;